package com.dsbj.mp.icardservice.controller.physicalcondition;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.mp.icardservice.controller.BaseController;
import com.dsbj.mp.icardservice.entity.DayPhysicalCondition;
import com.dsbj.mp.icardservice.entity.Employee;
import com.dsbj.mp.icardservice.entity.EmployeeWelfare;
import com.dsbj.mp.icardservice.entity.Persont;
import com.dsbj.mp.icardservice.model.MpUser;
import com.dsbj.mp.icardservice.service.EmployeeService;
import com.dsbj.mp.icardservice.service.EmployeeWelfareService;
import com.dsbj.mp.icardservice.service.PersontService;
import com.dsbj.mp.icardservice.service.physicalcondition.DayPhysicalConditionService;
import com.dsbj.mp.icardservice.utils.PropertyUtil;
import com.dsbj.mp.icardservice.utils.strprocess.ObjectParse;
import com.dsbj.mp.icardservice.utils.strprocess.StrUtil;
import com.dsbj.mp.icardservice.utils.strprocess.Time_convert;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * <p>
 * 每日健康检查表 前端控制器
 * </p>
 *
 * @author cjw
 * @since 2020-02-10
 */
@RestController
@RequestMapping("/physicalCondition")
public class DayPhysicalConditionController extends BaseController {
	
	@Resource
	private DayPhysicalConditionService dayPhysicalConditionService;
	
	@Resource
	private UcDayPhysicalCondition ucDayPhysicalCondition;
	
	@Resource
	private EmployeeService employeeService;
	
	@Resource
	private PersontService persontService;
	
	@Resource
	private EmployeeWelfareService employeeWelfareService;
	
	
	
	
	
	/**
	 * 根据公司编号获取公司名称
	 *
	 * @return
	 * @params
	 * @author cjw 2020/2/10
	 */
	@RequestMapping(value = "/getCompanynameByCompanyno")
	public ResponseMessage getCompanynameByCompanyno(String companyno) {
		Map<String, Object> map = new LinkedHashMap<>();
		map.put("01-02", "苏州东山精密");
		map.put("01-09", "苏州牧东");
		map.put("01-10", "苏州永创");
		map.put("01-11", "苏州诚镓");
		map.put("01-07", "盐城东山精密");
		map.put("01-08", "盐城通信");
		
		String companyname = ObjectParse.parse_toStr(map.get(companyno));
		if (companyname == null) {
			companyname = "暂时无数据";
		}
		return ResponseMessage.ok(companyname);
	}
	
	/**
	 * 获取员工手机号码。
	 * @param
	 * @return
	 * @author cjw 2020-02-19
	 */
	@RequestMapping(value = "/getEmplPhoneNumByIdcardno")
	public ResponseMessage getEmplPhoneNumByIdcardno(){
		MpUser mpUser=(MpUser) request.getAttribute("wxUser");
		
		ResponseMessage responseMessage_temp=ucDayPhysicalCondition.getEmplPhoneNumByIdcardno(mpUser);
		return responseMessage_temp;
	}
	
	/**
	 * 该用户昨天是否提交过 "健康状况信息"。
	 * @deprecated 待删
	 * @return
	 * @params
	 * @author cjw 2020/2/10
	 */
	@Deprecated
	@RequestMapping(value = "/hasYesterdayInfo")
	public ResponseMessage hasYesterdayInfo(HttpServletRequest request) {
		MpUser wxUser = (MpUser) request.getAttribute("wxUser");
		
		//获取昨天的日期《yyyy-MM-dd》
		long yesterday = new Date().getTime() - 24 * 60 * 60 * 1000L;
		String yesterday_date = Time_convert.convert_tostring(Time_convert.convert_todate(yesterday)).substring(0, 10);
		DayPhysicalCondition dayPhysicalCondition = dayPhysicalConditionService.getDayPhysicalConditionByCheckTime(
				wxUser.getIdcardno(), yesterday_date);
		
		//返回信息
		Map<String, Object> mapReturn = new LinkedHashMap<>();
		mapReturn.put("hasYesterdayInfo", 1);
		
		if (dayPhysicalCondition == null) {
			mapReturn.put("hasYesterdayInfo", 0);
			return ResponseMessage.ok(mapReturn);
		}
		return ResponseMessage.ok(mapReturn);
	}
	
	/**
	 * 是否展示"今天是否有更新"选项。
	 * 处理流程为：
	 * 1,若用户首次填写健康状况，则需要完整填写。
	 * 2,若用户完整填写了健康状况,则之后2天可不完整填写，第三天仍需要完整填写,接着2天又可不完整填写。
	 *
	 * 传入参数: checkTime
	 * @return
	 * @params
	 * @author cjw 2020/2/10
	 */
	@RequestMapping(value = "/showUpdateToday")
	public ResponseMessage showUpdateToday(String checkTime) {
		MpUser wxUser = (MpUser) request.getAttribute("wxUser");
		Map<String, Object> mapReturn = new LinkedHashMap<>();
		//默认展示该选项
		mapReturn.put("showUpdateToday", 1);
		
		/**
		 * 分析用户是否为首次填写
		 */
		QueryWrapper<DayPhysicalCondition> queryWrapper_dayPhysicalCondition = new QueryWrapper<DayPhysicalCondition>()
				.eq("IDCARDNO", wxUser.getIdcardno())
				.eq("STATUS", 1)
				.orderByDesc("CREATE_TIME");
		List<DayPhysicalCondition> list_dayPhysicalCondition = dayPhysicalConditionService.list(queryWrapper_dayPhysicalCondition);
		//若为首次填写
		if (list_dayPhysicalCondition.size() == 0) {
			mapReturn.put("showUpdateToday", 0);
			return ResponseMessage.ok(mapReturn);
		}
		
		/**
		 * 若用户曾填写过,获取"最近完整填写的"健康状况信息
		 */
		//复用queryWrapper_dayPhysicalCondition,list_dayPhysicalCondition
		queryWrapper_dayPhysicalCondition=null;
		list_dayPhysicalCondition=null;
		DayPhysicalCondition dayPhysicalCondition=null;
		queryWrapper_dayPhysicalCondition=new QueryWrapper<DayPhysicalCondition>()
				.eq("IDCARDNO",wxUser.getIdcardno())
				.lt("TO_CHAR(CHECK_TIME,'yyyy-mm-dd')",checkTime)
				.eq("UPDATE_TODAY",1)
				.eq("STATUS",1)
				.orderByDesc("CHECK_TIME");
		list_dayPhysicalCondition=dayPhysicalConditionService.list(queryWrapper_dayPhysicalCondition);
		//若checkTime之前不存在完整的健康状况信息
		if(list_dayPhysicalCondition.isEmpty()){
			mapReturn.put("showUpdateToday",0);
			return ResponseMessage.ok(mapReturn);
		}
		
		dayPhysicalCondition=list_dayPhysicalCondition.get(0);
		Date checkDate_pre=dayPhysicalCondition.getCheckTime();
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(checkDate_pre);
		calendar.add(Calendar.DAY_OF_MONTH,2);
		Date deadline=calendar.getTime();
		long diff=Time_convert.convert_todate(checkTime).getTime()-deadline.getTime();
		//若已超过两天,则需要完整填写
		if(diff>0){
			mapReturn.put("showUpdateToday",0);
			return ResponseMessage.ok(mapReturn);
		}
		//若在两天以内,可不完整填写
		return ResponseMessage.ok(mapReturn);
	}
	
	/**
	 * 存入每日健康状况信息。
	 *
	 * @return
	 * @params
	 * @author cjw 2020/2/10
	 */
	@RequestMapping(value = "/addPhysicalCondition")
	public ResponseMessage addDayPhysicalCondition(@RequestBody Map<String, Object> map) {
		
		/**
		 * 解析传来的参数
		 */
		MpUser wxUser=(MpUser)request.getAttribute("wxUser");
		DayPhysicalCondition dayPhysicalCondition = null;
		String str = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
		dayPhysicalCondition = JSON.parseObject(str, new TypeReference<DayPhysicalCondition>() {}, Feature.OrderedField);
		
		//StrUtil.prettyPrintWithTime("dayPhysicalCondition",dayPhysicalCondition);
		
		/**
		 * 0、验证部分。
		 */
		//判断checkTime对应的这一天是否可以提交健康状况信息。
		String checkTimeStr= Time_convert.convert_tostring(dayPhysicalCondition.getCheckTime()).substring(0,10);
		ResponseMessage responseMessage_temp=ucDayPhysicalCondition.canSubmitByCheckTime(wxUser,checkTimeStr);
		Map<String,Object> mapData=(Map<String, Object>) responseMessage_temp.getData();
		int canSubmit=ObjectParse.parse_toInt_elseException(mapData.get("canSubmit"));
		String message=ObjectParse.parse_toStr_elseException(mapData.get("message"));
		if(canSubmit==0){
			return ResponseMessage.error(message);
		}
		
		/**
		 * 1、用户可能输入了多余的信息，此处将部分字段置为空。
		 */
		//昨天下班或休息日"没有外出"
		if(dayPhysicalCondition.getOutYesterday()!=null && dayPhysicalCondition.getOutYesterday()==0){
			dayPhysicalCondition.setOutLocation(null);
			dayPhysicalCondition.setOutTransportDes(null);
			dayPhysicalCondition.setPersonOutTogether(null);
			dayPhysicalCondition.setOutTransport(null);
			dayPhysicalCondition.setOutTransportDes(null);
			dayPhysicalCondition.setPersonalProtect(null);
		}
		
		//今天没有更新
		if (dayPhysicalCondition.getUpdateToday() == 0) {
			//干咳
			dayPhysicalCondition.setDryCough(null);
			dayPhysicalCondition.setCoughSeeDoctor(null);
			dayPhysicalCondition.setCoughDiagResult(null);
			
			//胸闷
			dayPhysicalCondition.setChestTight(null);
			dayPhysicalCondition.setChestTightSeeDoctor(null);
			dayPhysicalCondition.setChestTightDiagResult(null);
			
			//其他症状
			dayPhysicalCondition.setOtherSymptom(null);
			dayPhysicalCondition.setSpecificDes(null);
			dayPhysicalCondition.setOtherSymptomSeeDoctor(null);
			dayPhysicalCondition.setOtherSymptomDiagResult(null);
			
			//身边发热者
			dayPhysicalCondition.setFeverPersonAround(null);
			dayPhysicalCondition.setRelationWithFeverPerson(null);
			
			//疑似肺炎患者
			dayPhysicalCondition.setPneumoniaAround(null);
			dayPhysicalCondition.setRelationWithPneumonia(null);
			dayPhysicalCondition.setRelationWithPneumoniaDes(null);
			
			//在本地或在外地
			dayPhysicalCondition.setWhereNow(null);
			dayPhysicalCondition.setLocation(null);
			dayPhysicalCondition.setPlanReturnTime(null);
			
			//待删 是否在岗
			//待删 dayPhysicalCondition.setDutyToday(null);
			
			//用"最近的完整的"健康状况信息,补充该dayPhysicalCondition,并返回该对象。
			responseMessage_temp = ucDayPhysicalCondition.supplementDayPhysicalCondition(dayPhysicalCondition);
			if (responseMessage_temp.isSuccess() == false) {
				return responseMessage_temp;
			}
			dayPhysicalCondition = (DayPhysicalCondition) responseMessage_temp.getData();
		}
		
		//今天有更新
		if (dayPhysicalCondition.getUpdateToday() == 1) {
			//干咳
			if (dayPhysicalCondition.getDryCough() == 0) {
				dayPhysicalCondition.setCoughSeeDoctor(null);
				dayPhysicalCondition.setCoughDiagResult(null);
			}
			
			//胸闷
			if (dayPhysicalCondition.getChestTight() == 0) {
				dayPhysicalCondition.setChestTightSeeDoctor(null);
				dayPhysicalCondition.setChestTightDiagResult(null);
			}
			
			//其他症状
			if (dayPhysicalCondition.getOtherSymptom() == 0) {
				dayPhysicalCondition.setSpecificDes(null);
				dayPhysicalCondition.setOtherSymptomSeeDoctor(null);
				dayPhysicalCondition.setOtherSymptomDiagResult(null);
			}
			
			//身边发热者
			if (dayPhysicalCondition.getFeverPersonAround() == 0) {
				dayPhysicalCondition.setRelationWithFeverPerson(null);
			}
			
			//身边疑似肺炎患者
			if (dayPhysicalCondition.getPneumoniaAround() == 0) {
				dayPhysicalCondition.setRelationWithPneumonia(null);
				dayPhysicalCondition.setRelationWithPneumoniaDes(null);
			}
			
			//在本地
			if ("苏州".equals(dayPhysicalCondition.getWhereNow()) || "盐城".equals(dayPhysicalCondition.getWhereNow())) {
				dayPhysicalCondition.setLocation(null);
				dayPhysicalCondition.setPlanReturnTime(null);
			}
			//存入图片路径(新的文件会覆盖旧的文件)
			String imagePath = PropertyUtil.getImageFileRoot() + "MYOU" + dayPhysicalCondition.getIdcardno() + ".jpg";
			if (saveBase64ToImageFile(dayPhysicalCondition.getPhotoBase64(), imagePath)) {
				dayPhysicalCondition.setPersonalTrajectoryUrl(PropertyUtil.getImageUrlRoot() + "MYOU" + dayPhysicalCondition.getIdcardno() + ".jpg");
			}
		}
		
		/**
		 * 2、存入每日健康状况信息
		 */
		dayPhysicalCondition.setStatus(1);
		dayPhysicalCondition.setCreateTime(new Date());
		dayPhysicalCondition.setCreateUser(wxUser.getName());
		dayPhysicalConditionService.save(dayPhysicalCondition);
		return ResponseMessage.ok();
	}
	
	/**
	 * 一个用户一天只能提交一次。
	 * @deprecated 待删
	 * @return
	 * @params
	 * @author cjw 2020/2/10
	 */
	@Deprecated
	public ResponseMessage submitOne_perDay(String idcardno) {
		String today_str = Time_convert.getCurrentTime().substring(0, 10);
		QueryWrapper<DayPhysicalCondition> queryWrapper = new QueryWrapper<DayPhysicalCondition>()
				.eq("IDCARDNO", idcardno)
				.eq("TO_CHAR(CHECK_TIME, 'yyyy-mm-dd')", today_str)
				.orderByDesc("CREATE_TIME");
		
		List<DayPhysicalCondition> list_dayPhysicalCondition = dayPhysicalConditionService.list(queryWrapper);
		
		if (list_dayPhysicalCondition.size() > 0) {
			return ResponseMessage.error("今天已提交健康状况信息");
		}
		return ResponseMessage.ok();
	}
	
	/**
	 * 判断checkTime对应的这一天是否可以提交健康状况信息。
	 * 该方法的流程为:
	 * 1,若该日期未到来,不可提交;
	 * 2,若该日期已到来, 若已提交过,不可再提交; 若没提交过,可提交。
	 *
	 * 传入参数: checkTime
	 * @return
	 * @params
	 * @author cjw 2020/2/10
	 */
	@RequestMapping(value = "/canSubmitByCheckTime")
	public ResponseMessage canSubmitByCheckTime(String checkTime) {
		MpUser wxUser = (MpUser) request.getAttribute("wxUser");
		
		ResponseMessage responseMessage_temp=ucDayPhysicalCondition.canSubmitByCheckTime(wxUser,checkTime);
		return responseMessage_temp;
	}
	
	
	
	@RequestMapping("/getTemperatureData")
	public ResponseMessage getTemperatureData(HttpServletRequest request) {
		MpUser wxUser = (MpUser) request.getAttribute("wxUser");
		List<DayPhysicalCondition> list = new ArrayList<>();
		if (StringUtils.isNotBlank(wxUser.getIdcardno())) {
			list = dayPhysicalConditionService.getTemperatureData(wxUser.getIdcardno());
		}
		return ResponseMessage.ok(list);
	}
	
	//对字节数组字符串进行Base64解码并生成图片
	private boolean saveBase64ToImageFile(String imgStr, String imagePath) {
		if (imgStr == null) //图像数据为空
			return false;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			//Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {//调整异常数据
					b[i] += 256;
				}
			}
			//生成jpeg图片
			OutputStream out = new FileOutputStream(imagePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			logger.error("将base64格式的字符串编码,并存入对应的图片文件中，发生错误!" + e.toString());
			return false;
		}
	}
	
	/**
	 *
	 * @param
	 * @return
	 * @author cjw 2020-02-15
	 */
	public static void main(String[] args){
	
		
	}
	
	
}
